// script.js
//document.addEventListener('DOMContentLoaded', () => {
// 显示登录表单
function showLoginForm() {
    document.getElementById('loginContainer').style.display = 'block';
    document.getElementById('registerContainer').style.display = 'none';
    document.getElementById('managementContainer').style.display = 'none';
    document.getElementById('addStaffContainer').style.display = 'none';
    document.getElementById('departmentContainer').style.display = 'none';
    document.getElementById('employeechangeContainer').style.display = 'none';
    document.getElementById('nav').style.display = 'none';
}
showLoginForm(); // 默认显示登录表单
// 显示注册表单
function showRegisterForm() {
    document.getElementById('loginContainer').style.display = 'none';
    document.getElementById('registerContainer').style.display = 'block';
    document.getElementById('managementContainer').style.display = 'none';
    document.getElementById('addStaffContainer').style.display = 'none';
    document.getElementById('departmentContainer').style.display = 'none';
    document.getElementById('employeechangeContainer').style.display = 'none';
    document.getElementById('nav').style.display = 'none';
}

// 登录功能
document.getElementById('loginForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const response = await fetch('/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    });
    const data = await response.json();
    if (data.success) {
        showManagementForm(); // 登录成功，显示管理界面
    } else {
        document.getElementById('loginMessage').innerText = '登录失败，请重试。';
    }
});

// 注册功能
document.getElementById('registerForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = document.getElementById('registerUsername').value;
    const password = document.getElementById('registerPassword').value;
    const response = await fetch('/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    });
    const data = await response.json();
    if (data.success) {
        document.getElementById('registerMessage').innerText = '注册成功，请登录。';
        showLoginForm(); // 注册成功，返回登录界面
    } else {
        document.getElementById('registerMessage').innerText = '注册失败，请重试。';
    }
});

// 显示管理界面
function showManagementForm() {
    document.getElementById('nav').style.display = 'block';
    document.getElementById('loginContainer').style.display = 'none';
    document.getElementById('registerContainer').style.display = 'none';
    document.getElementById('managementContainer').style.display = 'block';
    document.getElementById('addStaffContainer').style.display = 'none';
    document.getElementById('departmentContainer').style.display = 'none';
    document.getElementById('employeechangeContainer').style.display = 'none';
    loadStaff(); // 加载学生数据
}

// 显示添加学生界面
function showAddStaffForm() {
    document.getElementById('nav').style.display = 'block';
    document.getElementById('loginContainer').style.display = 'none';
    document.getElementById('registerContainer').style.display = 'none';
    document.getElementById('managementContainer').style.display = 'none';
    document.getElementById('addStaffContainer').style.display = 'block';
    document.getElementById('departmentContainer').style.display = 'none';
    document.getElementById('employeechangeContainer').style.display = 'none';
    document.getElementById('addStaffForm').reset();
}

// 显示部门信息页面
function showDepartmentForm() {
    document.getElementById('nav').style.display = 'block';
    document.getElementById('loginContainer').style.display = 'none';
    document.getElementById('registerContainer').style.display = 'none';
    document.getElementById('managementContainer').style.display = 'none';
    document.getElementById('addStaffContainer').style.display = 'none';
    document.getElementById('departmentContainer').style.display = 'block';
    document.getElementById('employeechangeContainer').style.display = 'none';
    loadDepartment(); // 加载部门信息
}

// 显示人员变更信息页面
function showPersonchangeForm() {
    document.getElementById('nav').style.display = 'block';
    document.getElementById('loginContainer').style.display = 'none';
    document.getElementById('registerContainer').style.display = 'none';
    document.getElementById('managementContainer').style.display = 'none';
    document.getElementById('addStaffContainer').style.display = 'none';
    document.getElementById('departmentContainer').style.display = 'none';
    document.getElementById('employeechangeContainer').style.display = 'block';
    loadPersonchange(); // 加载人员变更信息
}

// 加载部门信息
async function loadDepartment() {
    const response = await fetch('/departments');
    const data = await response.json();
    const tbody = document.getElementById('departmentTableBody');
    tbody.innerHTML = ''; // 清空表格内容
    data.forEach(staff => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
                <td>${staff.id}</td>
                <td>${staff.name}</td>
                <td>${staff.manager}</td>
                <td>${staff.intro}</td>
            `;
        tbody.appendChild(tr);
    });
}

// 加载人员变更信息
async function loadPersonchange() {
    const response = await fetch('/employeechange');
    const data = await response.json();
    const tbody = document.getElementById('employeechangeTableBody');
    tbody.innerHTML = ''; // 清空表格内容
    data.forEach(staff => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
                <td>${staff.id}</td>
                <td>${staff.name}</td>
                <td>${staff.situation}</td>
                <td>${staff.intro}</td>
            `;
        tbody.appendChild(tr);
    });

    console.log(8889);
}

// position 就是 job

// 加载学生数据
async function loadStaff() {
    const response = await fetch('/staffs');
    const data = await response.json();
    console.log(data);
    const tbody = document.getElementById('staffTableBody');
    tbody.innerHTML = ''; // 清空表格内容
    data.forEach(staff => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
                <td>${staff.id}</td>
                <td>${staff.authority}</td>
                <td>${staff.name}</td>
                <td>${staff.sex}</td>
                <td>${staff.birthday}</td>
                <td>${staff.department}</td>
                <td>${staff.position}</td>
                <td>${staff.education}</td>
                <td>${staff.skill}</td>
                <td>${staff.address}</td>
                <td>${staff.tel}</td>
                <td>${staff.email}</td>
                <td>${staff.status}</td>
                <td>${staff.remark}</td>
                <td><button class="updateInf">修改</button><button class="deleteInf">删除</button></td>
            `;
        tbody.appendChild(tr);
    });
    // 添加修改和删除按钮的事件监听器
    Array.from(document.querySelectorAll('.updateInf')).forEach(button => {
        button.addEventListener('click', (event) => {
            var button = event.target;
            var row = button.parentNode.parentNode;
            if (true) {
                // 调用修改员工信息的函数（请根据实际API进行调整）
                updateEmployee(row);
            }
        });
    });

    Array.from(document.querySelectorAll('.deleteInf')).forEach(button => {
        button.addEventListener('click', (event) => {
            var button = event.target;
            var row = button.parentNode.parentNode;
            if (confirm('您确定要删除该员工吗？')) {
                // 调用删除员工信息的函数（请根据实际API进行调整）
                deleteEmployee(row);
            }
        });
    });
}

// 查找员工数据
document.getElementById('searchEmployeeForm').addEventListener('submit', (e) => {
    e.preventDefault();
    const keyword = document.getElementById('searchInput').value;
    const term = document.getElementById('searchCriteria').value;
    if (keyword == '') {
        loadStaff();
    }
    else {
        const response = fetch(`/search?term=${term}&keyword=${keyword}`);
        response.then(response => response.json())
            .then(data => {
                const tbody = document.getElementById('staffTableBody');
                tbody.innerHTML = ''; // 清空表格内容
                if (data.length == 0) {
                    const row = `<tr><td colspan="14">未找到匹配的员工</td></tr>`;
                    tbody.innerHTML += row;
                }
                else {
                    data.forEach(staff => {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                    <td>${staff.id}</td>
                    <td>${staff.authority}</td>
                    <td>${staff.name}</td>
                    <td>${staff.sex}</td>
                    <td>${staff.birthday}</td>
                    <td>${staff.department}</td>
                    <td>${staff.position}</td>
                    <td>${staff.education}</td>
                    <td>${staff.skill}</td>
                    <td>${staff.address}</td>
                    <td>${staff.tel}</td>
                    <td>${staff.email}</td>
                    <td>${staff.status}</td>
                    <td>${staff.remark}</td>
                    <td><button class="updateInf">修改</button><button class="deleteInf">删除</button></td>
                    `;
                        tbody.appendChild(tr);
                    });
                }

            });
    }
});


function deleteEmployee(row) {
    const id = row.cells[0].innerText;
    // 发起请求更新员工信息
    fetch('/delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id })
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                alert('删除成功');
                showManagementForm(); // 加载学生数据
            } else {
                alert('删除失败');
            }
        })
        .catch(error => {
            console.error('There has been a problem with your fetch operation:', error);
            alert('请求失败，请稍后重试。');
        });
}

function updateEmployee(row) {
    // 先获取该员工的原始数据
    // 填充表单数据, 同时这份数据也要发送给后端，用于确定要修改的是哪个值
    const olddata = {
        id: row.cells[0].innerText,
        authority: row.cells[1].innerText,
        name: row.cells[2].innerText,
        sex: row.cells[3].innerText,
        birthday: row.cells[4].innerText,
        department: row.cells[5].innerText,
        position: row.cells[6].innerText,
        education: row.cells[7].innerText,
        skill: row.cells[8].innerText,
        address: row.cells[9].innerText,
        tel: row.cells[10].innerText,
        email: row.cells[11].innerText,
        status: row.cells[12].innerText,
        remark: row.cells[13].innerText,
    }
    document.getElementById('employee-Id').value = olddata.id;
    document.getElementById('employee-Name').value = olddata.name;
    document.getElementById('employee-Authority').value = olddata.authority;
    document.getElementById('employee-Sex').value = olddata.sex;
    document.getElementById('employee-Birthday').value = olddata.birthday;
    document.getElementById('employee-Department').value = olddata.department;
    document.getElementById('employee-Position').value = olddata.position;
    document.getElementById('employee-Education').value = olddata.education;
    document.getElementById('employee-Skill').value = olddata.skill;
    document.getElementById('employee-Address').value = olddata.address;
    document.getElementById('employee-Tel').value = olddata.tel;
    document.getElementById('employee-Email').value = olddata.email;
    document.getElementById('employee-Status').value = olddata.status;
    document.getElementById('employee-Remark').value = olddata.remark;

    // 显示表单
    document.getElementById('updateEmployeeModal').style.display = 'block';

    // 处理表单提交
    document.getElementById('updateEmployeeForm').onsubmit = function (e) {
        e.preventDefault();
        const updatedData = {
            id: document.getElementById('employee-Id').value,
            authority: document.getElementById('employee-Authority').value,
            name: document.getElementById('employee-Name').value,
            sex: document.getElementById('employee-Sex').value,
            birthday: document.getElementById('employee-Birthday').value,
            department: document.getElementById('employee-Department').value,
            position: document.getElementById('employee-Position').value,
            education: document.getElementById('employee-Education').value,
            skill: document.getElementById('employee-Skill').value,
            address: document.getElementById('employee-Address').value,
            tel: document.getElementById('employee-Tel').value,
            email: document.getElementById('employee-Email').value,
            status: document.getElementById('employee-Status').value,
            remark: document.getElementById('employee-Remark').value
        };

        if (confirm('您确定要修改该员工吗？')) {
            // 发起请求更新员工信息
            fetch('/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ olddata, updatedData })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert('修改成功');
                        document.getElementById('updateEmployeeModal').style.display = 'none';
                        showManagementForm(); // 加载学生数据
                    } else {
                        alert('修改失败');
                    }
                })
                .catch(error => {
                    console.error('There has been a problem with your fetch operation:', error);
                    alert('请求失败，请稍后重试。');
                });
        }
    };

};

// 处理取消按钮
document.getElementById('cancelUpdate').onclick = function () {
    document.getElementById('updateEmployeeModal').style.display = 'none';
};


// 添加员工数据
document.getElementById('addStaffForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    // const id = document.getElementById('addStaffId').value;
    const authority = document.getElementById('addStaffAuthority').value;
    const name = document.getElementById('addStaffName').value;
    const sex = document.getElementById('addStaffSex').value;
    const birthday = document.getElementById('addStaffBirthday').value;
    const department = document.getElementById('addStaffDepartment').value;
    const position = document.getElementById('addStaffPosition').value;
    const education = document.getElementById('addStaffEducation').value;
    const skill = document.getElementById('addStaffSkill').value;
    const address = document.getElementById('addStaffAddress').value;
    const tel = document.getElementById('addStaffTel').value;
    const email = document.getElementById('addStaffEmail').value;
    const status = document.getElementById('addStaffStatus').value;
    const remark = document.getElementById('addStaffRemark').value;
    const response = await fetch('/add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ authority, name, sex, birthday, department, position, education, skill, address, tel, email, status, remark })
    });
    const data = await response.json();
    if (data.success) {
        document.getElementById('addStaffMessage').innerText = '添加学生成功！';
        showManagementForm(); // 加载学生数据
    } else {
        document.getElementById('addStaffMessage').innerText = '添加学生失败，请重试。';
    }
});

document.getElementById('management-interface').addEventListener('click',async () => {
    showManagementForm();
    console.log(8679);
});

document.getElementById('personnel-change-record').addEventListener('click',async () => {
    showPersonchangeForm();
    console.log(8889);
});

document.getElementById('department-information').addEventListener('click',async ()=> {
    showDepartmentForm();
    console.log(8879);
});



